package cn.zjh.base.controller;

import cn.zjh.base.config.FastdfsUtil;
import cn.zjh.base.utils.AjaxResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastController {



    /**
    * @Title: upload
    * @Description: 文件下载
    * @Author: Mr.Zhang
    * @Version: 1.0
    * @Date:  2022/7/2 0:41
    * @Parameters:(@RequestPart(value = "file",required = true)  val
    * @Return
    */
    @PostMapping
    public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile multipartFile){
        try {
            //得到文件的byte数组
            byte[] bytes = multipartFile.getBytes();
            //通过工具类得到文件后缀
            String suffix = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
            //调用fastdfs的文件上传工具类，得到地址+后缀
            String filePath = FastdfsUtil.upload(bytes, suffix);
            return AjaxResult.me().setResultObj(filePath);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败，请重试！！！");
        }
    }


    /**
     * @Title: upload
     * @Description: 文件删除接口
     * @Author: Mr.Zhang
     * @Version: 1.0
     * @Date:  2022/7/2 0:41
     * @Parameters:(@RequestPart(value = "file",required = true)  val
     * @Return
     */
    @DeleteMapping
    public AjaxResult upload(@RequestParam(value = "filePath",required = true) String filePath){
        try {
            // 因为删除需要组名+图片路径，所以我们需要把前端传递进来的图片路径进行分割
            // /group1/M00/00/05/oYYBAGKCO-6AdKyoAAEOykzR2Hc97_350x350.jpeg
            // 1.得到组名和路径名称
            // 1.1.得到组名
            String pathTmp = filePath.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            // 1.2.得到图片路径
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            // 2.调用工具类方法进行删除，传递组名和图片路径名称
            FastdfsUtil.delete(groupName, remotePath);
            return AjaxResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败，请重试！！！");
        }
    }





}
